/*
 * @Description: 路由拦截状态管理
 * @Author: liushuang
 * @Date: 2022-03-27 14:47:46
 * @LastEditTime: 2022-09-05 17:48:24
 */
import { asyncRoutes, constantRoutes } from '@/router'
import { filterRoutes, setNewRoutes, setRoutesRedirect } from '@/router/routes'

const states = () => ({
  routes: [],
  asyncRoutes: [],
  secondRouts: [] // 一级路由下的子路由，每次切换一级路由时改变
})

const getters = {
  routes: (state) => state.routes
}

const mutations = {
  setRoutes(state, routes) {
    state.routes = routes
  },
  setAsyncRoutes(state, asyncR) {
    state.asyncRoutes = asyncR
  },
  setSecondRouts(state, children) {
    state.secondRouts = children
  }
}

const actions = {
  async setRoutes({ commit }) {
    // 不能用深拷贝，不然每次路由变化会重新加载侧边栏组件
    const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes])
    // 将三级以上的路由全部转为二级路由，确保可以被keep-alive缓存
    const newAsyncRoutes = setRoutesRedirect(setNewRoutes(finallyRoutes))
    commit('setRoutes', finallyRoutes)
    commit('setAsyncRoutes', asyncRoutes)
    return [...newAsyncRoutes]
  }
}

export default {
  state: states, getters, mutations, actions
}
